package cn.blu10ph.trustshare.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.BaseEncoding;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

/**
 * <p> ConvertUtil </p >
 *
 * @author cxx
 * @date 2024/4/6 22:30
 */
public class ConvertUtil {

    protected static final ObjectMapper MAPPER = new ObjectMapper();

    public static byte[] str2Byte(String str) {
        return Base64.getMimeDecoder().decode(str);
    }

    public static String byte2String(byte[] bytes) {
        return Base64.getMimeEncoder().encodeToString(bytes);
    }

    public static byte[] str2Hex(String str) {
        return BaseEncoding.base16().decode(str);
    }

    public static String hex2String(byte[] bytes) {
        return BaseEncoding.base16().encode(bytes).toUpperCase();
    }

    public static <T> T str2Obj(String json, Class<T> clazz) throws JsonProcessingException {
        return MAPPER.readValue(json, clazz);
    }

    public static <T> List<T> str2List(String json, Class<T> clazz) throws JsonProcessingException {
        JavaType javaType = MAPPER.getTypeFactory().constructCollectionType(List.class, clazz);
        return MAPPER.readValue(json, javaType);
    }

    public static <T> String obj2Str(T msgObj) throws JsonProcessingException {
        return MAPPER.writeValueAsString(msgObj);
    }

    public static ByteBuf str2ByteBuf(String msg) {
        return Unpooled.copiedBuffer(msg.getBytes(StandardCharsets.UTF_8));
    }

}
